package com.wg.dome.handle;

import com.wg.dome.ClientPeer;
import com.wg.dome.ErrorHelper;
import com.wg.dome.entity.user.AccountEntity;
import com.wg.dome.operation.StartGameRequest;
import com.wg.dome.operation.StartGameResponse;
import com.wg.dome.repository.AccountRepository;
import com.wg.core.net.OperationRequest;
import com.wg.core.net.OperationResponse;
import com.wg.core.net.SendParameters;

/**
 * 开始游戏
 */
public class HandleRequest1 extends BaseHandle {

    @Override
    public OperationResponse execute(ClientPeer peer, OperationRequest request, SendParameters sendParameters) {
        StartGameRequest startGameRequest = new StartGameRequest(request);
        if (!startGameRequest.isValid()) {
            return ErrorHelper.getInvalidResponse(startGameRequest);
        }

        AccountRepository repository = new AccountRepository();
        AccountEntity accountEntity = repository.get(startGameRequest.getClientId());
        if (accountEntity == null) {
            accountEntity = new AccountEntity();
            accountEntity.setClientId(startGameRequest.getClientId());
            accountEntity.setPlayerId(-1);
            repository.add(accountEntity);
        }

        if (accountEntity.getPlayerId() > 0) {
            peer.setPlayerId(accountEntity.getPlayerId());
        }

        StartGameResponse startGameResponse = new StartGameResponse();
        startGameResponse.setPlayerId(accountEntity.getPlayerId());
        return new OperationResponse(request.getOperationCode(), startGameResponse);
    }
}
